/* eslint-disable no-unused-vars */
/*
 * @Description:
 * @Author: huangmin
 * @Email: huangmin@nnuo.com
 * @Date: 2022-01-17 09:16:09
 * @LastEditors: huangmin
 * @LastEditTime: 2022-03-19 17:43:58
 * @FilePath: \jiulipu_penguin\src\utils\utils.js
 */
import axios from '@/axios';
import Taro from '@tarojs/taro';
import {
  login
} from '@/axios/api/user';
import toast from '@/utils/toast';
import {
  qiNiuUrl,
  qiNiuImage
} from '@/utils/config';

export const getToken = (payload) => {
  console.log(payload);
  return new Promise((resolve) => {
    axios.post(login, {
      ...payload
    }).then(res => {
      const {
        code,
        data
      } = res
      if (code === 200) {
        const {
          userInfo,
          token
        } = data;
        Taro.setStorageSync('userInfo', userInfo);
        Taro.setStorageSync('token', token);
        Taro.setStorageSync('datetime', new Date().toLocaleString());
        setTimeout(() => {
          Taro.hideLoading();
          toast.success("登录成功");
        }, 300);
        resolve({
          userInfo,
          token
        });
      } else {
        resolve(false);
      }
    })
  })

}
export const getUserInfo = () => {
  // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
  // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
  return new Promise(resolve => {
    Taro.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: ({
        userInfo
      }) => {
        Taro.showLoading({
          title: '登录中...',
          mask: true
        })
        Taro.login({
          success: async ({
            code
          }) => {
            let data = await getToken({
              userInfo,
              code
            });
            if (data) {
              resolve(data);
            } else {
              toast.error("登录失败");
              resolve(false);
            }
          }
        })
      },
      fail: () => {
        toast.error("登录失败");
        resolve(false);
      }
    })
  })
}
export const getNavbarHight = () => {
  const {
    statusBarHeight,
    windowWidth
  } = Taro.getSystemInfoSync();
  const menuButtonObject = Taro.getMenuButtonBoundingClientRect();
  const {
    top,
    height,
    right
  } = menuButtonObject;
  const gap = top - statusBarHeight;
  const navBarHeight = height + gap * 2;
  const menuGap = windowWidth - right;
  // 计算状态栏与导航栏的总高度
  const statusNavBarHeight = statusBarHeight + navBarHeight;
  return statusNavBarHeight;
}
export const getImageInfo = (src) => {
  return new Promise(resovle => {
    Taro.getImageInfo({
      src,
      success: ({
        width,
        height
      }) => {
        resovle({
          width,
          height
        })
      }
    })
  })
}
export const chooseImage = (count = 1, size = false, sourceType = ['album', 'camera'], ) => {
  return new Promise(resovle => {
    Taro.chooseImage({
      count,
      sourceType,
      success: async ({
        tempFilePaths
      }) => {
        let arr = [];
        for (const item of tempFilePaths) {
          if (size) {
            const {
              width,
              height
            } = await getImageInfo(item);
            arr.push({
              url: item,
              width,
              height
            })
          } else {
            arr.push({
              url: item,
            })
          }
        }
        resovle(arr);
      },
    }).catch(err => {
      // console.log(err);
    })
  })
}
export const getExt = (name) => {
  const reg = /\.([0-9a-zA-Z]+)(?:[?#]|$)/i;
  // 获得文件扩展名
  const fileExt = name.match(reg);
  return fileExt ? `.${fileExt[1]}` : '';
};
export const compress = (src) => {
  return new Promise(resovle => {
    Taro.compressImage({
      src, // 图片路径
      success: ({
        tempFilePath
      }) => {
        resovle(tempFilePath)
      }
    })
  })
}
export const createUUID = () => {
  let d = new Date().getTime();
  let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
};
export const wxUpload = (filePath, token, key) => {
  return new Promise((resovle, reject) => {
    Taro.uploadFile({
      url: qiNiuUrl,
      filePath,
      name: 'file',
      formData: {
        token: token,
        key,
      },
      success(res) {
        //do something
        const data = JSON.parse(res.data);
        if (data.key) {
          resovle(qiNiuImage + data.key)
        } else {
          reject(false)
        }
      },
      fail: (err) => {
        reject(err);
      }
    }).catch(err => {
      reject(err)
    })
  })
}
export const uploadQiniu = (tempFilePaths, token, path, option = {}) => {
  return new Promise(async (resovle, reject) => {
    if (path === 'avatar/' || path === 'cover/' || path === 'recipe/') {
      const {
        isCompress = true,
          multi = false
      } = option
      if (!multi) {
        const file = tempFilePaths[0];
        const {
          url,
          width,
          height
        } = file;
        const filePath = isCompress ? await compress(url) : url;
        const realExt = getExt(url);
        let key = '';
        if (width && height) {
          key = path + createUUID() + `_${width}w_${height}h` + realExt;
        } else {
          key = path + createUUID() + realExt;
        }
        Taro.showLoading({
          title: '上传中',
          mask: true
        })
        try {
          let d = await wxUpload(filePath, token, key);
          resovle(d)
        } catch (err) {
          Taro.hideLoading();
          reject(err);
        }
        Taro.hideLoading();
      } else {
        let arr = [];
        let count = 0;
        for (const file of tempFilePaths) {
          count++;
          const {
            url
          } = file;
          const filePath = isCompress ? await compress(url) : url;
          const realExt = getExt(url);
          let key = path + createUUID() + realExt;
          Taro.showLoading({
            title: `第${count}张上传中`,
            mask: true
          });
          try {
            let d = await wxUpload(filePath, token, key);
            arr.push(d);
          } catch (err) {
            reject(`第${count}张上传失败`);
            Taro.hideLoading();
          }
        }
        Taro.hideLoading();
        resovle(arr);
      }
    }
  })

}
